<script setup lang="ts">
import { computed, ref, h } from 'vue'
import type {} from 'vue'
import { NMenu } from 'naive-ui'
import type { MenuOption } from 'naive-ui'
import { HomeOutline, SettingsOutline, BasketballOutline } from '@vicons/ionicons5'
import type { PermissionItemType } from '@/types/api/permission'
import { useRoute, useRouter } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import { renderIcon } from '@/utils/common'

const router = useRouter()
const route = useRoute()
const permissionStore = usePermissionStore()

// 构建菜单的的key
const buildMenuKey = (permission: PermissionItemType): string => {
  return `${permission.id}_${permission.path}`
}

// 当前已展开的菜单key
const expendedKeys = ref<string[]>([])
// 当前选中的菜单key
const currentKey = computed(() => {
  const stack = [...permissionStore.permission]
  let parentPermission = null
  let currentPermission = null
  while (stack.length > 0) {
    const permission = stack.pop() as PermissionItemType
    if (permission.path === route.path) {
      // 找到目标菜单
      currentPermission = permission
      parentPermission && expendedKeys.value.push(buildMenuKey(parentPermission))
      break
    } else {
      // 没找到目标菜单
      if (permission.children.length > 0) {
        parentPermission = permission
        expendedKeys.value.push(buildMenuKey(parentPermission))
        permission.children.forEach((child) => stack.push(child))
      } else {
        parentPermission = null
      }
    }
  }
  return currentPermission ? `${currentPermission.id}_${currentPermission.path}` : `0_/`
})

// 菜单name-icon 映射
const menuIconMap: Record<string, ReturnType<typeof renderIcon>> = {
  首页: renderIcon(HomeOutline),
  平台设置: renderIcon(SettingsOutline),
  default: renderIcon(BasketballOutline)
}
// 公共菜单
const sharedOptions: MenuOption[] = [
  {
    label: '首页',
    key: '0_/',
    icon: menuIconMap.首页
  }
]

// 菜单配置
const menuOptions = computed(() => {
  return sharedOptions.concat(traversePermission(permissionStore.permission))
})
// 递归遍历权限，返回菜单配置
const traversePermission = (permissions: PermissionItemType[]): MenuOption[] => {
  return permissions
    .filter(({ type }) => type === 'menu')
    .map((permission) => {
      const { id, path, permissionName, children } = permission
      const menuChildren = children.filter(({ type }) => type === 'menu')
      return {
        label: permissionName,
        key: buildMenuKey(permission),
        children: menuChildren.length ? traversePermission(menuChildren) : undefined,
        icon: !path ? menuIconMap[permissionName] || menuIconMap['default'] : undefined
      }
    })
}

// 菜单选中值变化
const handleMenuValueChange = (key: string, item: MenuOption) => {
  const [_, path] = key.split('_')
  path && router.push(path)
}
</script>

<template>
  <div class="container">
    <NMenu
      :options="menuOptions"
      :root-indent="16"
      :default-expanded-keys="expendedKeys"
      :value="currentKey"
      @update:value="handleMenuValueChange"
    ></NMenu>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 180px;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  border-right: 1px solid #ddd;
}
</style>
